package com.qf.service.serviceimpl;

import com.qf.dao.OrderDao;
import com.qf.dao.daoimpl.OrderDaoImpl;
import com.qf.pojo.Order;
import com.qf.pojo.OrderItem;
import com.qf.pojo.PageBean;
import com.qf.service.OrderService;
import com.qf.utils.dbutilUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Mr.Liu
 * @date 2021/11/27 17:53
 */

public class OrderServiceImpl implements OrderService {
    /**
     * 生成订单
     * @param order
     */
    @Override
    public void addOrder(Order order) {
        Connection connection = null;
        try {
            connection = dbutilUtils.getConnection();
            System.out.println(connection);
            connection.setAutoCommit(false);//禁止自动提交,开启事务
            OrderDao od = new OrderDaoImpl();
            od.addOrder(order);
            List<OrderItem> orderItems = order.getOrderItems();
            for(OrderItem orderItem : orderItems){
                od.addOrderItem(orderItem);
            }
            connection.commit();//提交事务
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

    }

    /**
     * 查询订单列表
     * @param currentPage
     * @param pageSize
     * @param uid
     * @return
     */
    @Override
    public PageBean<Order> foundOrder(int currentPage, int pageSize, String uid) {
        try {
            OrderDao od = new OrderDaoImpl();
            List<Order> list = od.foundOrderByPage(currentPage,pageSize,uid);
            int totalSize = od.foundTotalSize(uid);
            PageBean pageBean = new PageBean<>(currentPage,pageSize,totalSize,list);
            if(pageBean!=null){
                return pageBean;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
